<template>
  <el-dialog
    custom-class="montyly-account"
    v-el-drag-dialog="{ drag: true, full: false, resize: true }"
    title="月现金结算"
    :close-on-click-modal="false"
    :visible="true"
    @close="closeMd"
    width="80%"
    append-to-body>
    <div ref="dgtools" class="filter-container">
      <div class="dgts-row">
        <el-form :inline="true">
          <el-form-item label="结算月份">
            <el-date-picker
              clearable 
              type="month" 
              value-format="yyyy-MM"
              format="yyyy年MM月"
              placeholder="结算月份"
              v-model="dg.ps.settleMonth" 
              @change="onSettleMonthChange"
              :picker-options="settleMonthOptions"
              style="width: 130px;"
            />
          </el-form-item>

          <el-button 
            type="primary" 
            icon="el-icon-search" 
            @click="queryDgList">
            搜索
          </el-button>

          <el-button 
            type="primary" 
            icon="el-icon-s-order"
            @click="onSubmit">
            确认结算
          </el-button>
        </el-form>

        <div class="dgts-text-tj1" style="margin-left: 20px;">
          <b class="tr-it-title">累计</b>
          <el-divider direction="vertical"></el-divider>
          <b class="tr-it c-green">收入 {{ totalPay || 0 }}元</b>
          <el-divider direction="vertical"></el-divider>
          <b class="tr-it c-red">支出 {{ totalGath || 0 }}元</b>
          <el-divider direction="vertical"></el-divider>
          <b class="tr-it c-blue">余额 {{ bankBalance || 0 }}元</b>
        </div>
      </div>
    </div>

    <el-table
      :ref="dg.tbName"
      :data="dg.list"
      row-key="id"
      :height="bodyHeight - 60"
      border fit
      :row-class-name="rowClassName"
      @header-dragend="dragHeader"
      @selection-change="selRowChange">
      <el-table-column 
        v-for="(col, index) in dg.columns" 
        :key="index"
        :class-name="dg.dgName"
        :prop="col.field"
        :label="col.label"
        :width="col.width">
        <template slot-scope="{row}">
          <template v-if="col.field == 'operUser'">
            {{row.operUser ? row.operUser : '--'}}
          </template>

          <template v-else-if="col.field == 'isCheck'">
            <span v-if="row.isCheck == -1" class="c-green">已结算</span>
            <span v-else-if="row.isCheck == 0" class="c-red">未操作</span>
            <span v-else class="c-bbb">已报销</span>
          </template>

          <template v-else-if="col.field == 'cusName'">
            {{row.cusName ? row.cusName.split('-')[0] : '--'}}
          </template>

          <template v-else-if="col.field == 'operNote'">
            <span v-html="row.operNote.replace(/\(/g, '<br />').replace(/\)/g, '；<br />').replace(/&nbsp;,/g, '<br />')"></span>
          </template>

          <template v-else-if="col.field == 'settleUser'">
            {{ row.settleUser && row.settleUser.realName+'-'+row.settleUser.phone }}
          </template>

          <template v-else-if="col.field == 'tradeInMoney'">
            <span :class="row.tradeInMoney > 0 ? 'c-green' : ''">{{row.tradeInMoney}} 元</span>
          </template>

          <template v-else-if="col.field == 'tradeOutMoney'">
            <span :class="row.tradeOutMoney > 0 ? 'c-red' : ''">{{row.tradeOutMoney}} 元</span>
          </template>

          <template v-else>{{getColVal(row, col.field)}}</template>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="dg.total"
      :page.sync="dg.ps.page"
      :limit.sync="dg.ps.rows"
      @pagination="getDgList"
    />
  </el-dialog>
</template>

<script>
import DataGridBase from "@/views/mixins/DataGridBase";
import DataGridResize from "@/views/mixins/DataGridResize";
import elDragDialog from "@/directive/el-drag-dialog";
import Pagination from "@/components/Pagination";

import * as orderSer from "@/api/services/order.service";

import AddAccount from "../add-account";
import UpdateAccount from "../update-account";

export default {
  name: "MonthlyAccount",
  mixins: [DataGridBase, DataGridResize],
  directives: { elDragDialog },
  components: {Pagination, AddAccount, UpdateAccount},
  computed: {
    getBalance() {
      let reg = /^[0-9]+.?[0-9]*$/;
      let result = reg.test(this.bankBalance) ? '元' : ''
      return this.bankBalance + result
    }
  },
  data() {
    let cols = [
      {label: '标示号', field: 'unitNum', width: 80},
      {label: '交易时间', field: 'tradeTime', width: 140},
      {label: '下账人', field: 'operUser', width: 100},
      {label: '银行名称', field: 'myBankName', width: 180},
      {label: '我的银行账号', field: 'myBankNum', width: 150},
      {label: '报销状态', field: 'isCheck', width: 80},
      {label: '金额类型', field: 'moneyTypeId.typeName', width: 120},
      {label: '客户名称', field: 'cusName', width: 140},
      {label: '借', field: 'tradeInMoney', width: 80},
      {label: '对方户名', field: 'transName', width: 150},
      {label: '对方账号', field: 'transNum', width: 120},
      {label: '添加时间', field: 'addTime', width: 140},
      {label: '贷', field: 'tradeOutMoney', width: 80},
      {label: '余额', field: 'balance', width: 80},
      {label: '摘要', field: 'remark', width: 320},
      {label: '操作备注', field: 'opermark', width: 100},
    ];
    let that = this;
    return {
      // 总支付
      totalPay: 0,
      // 总收入
      totalGath: 0,
      // 银行余额
      bankBalance: 0,

      // 结算月份设置
      settleMonthOptions: {
        disabledDate(time) {
          // 只能选择小于当月的月份
          const dd = new Date();
          dd.setMonth(dd.getMonth() - 1);
          return time > dd;
        }
      },

      dg: {
        dgName: 'dg',
        tbName: "monthlyAccountTb",
        total: 0,
        list: [],
        srcCols: cols,
        columns: [],
        selRows: [],
        ps: {
          // 过滤参数
          page: 1, rows: 20,
          // 结算月份
          settleMonth: '',
          // 结束时间
          eTime: "", 
          // 开始时间
          sTime: "",
          // 结算类型
          settleType: 0,
        },

      }
    };
  },
  mounted() {
    const that = this;

    let mothTotalDays = that.dg.ps.settleMonth = that.$moment().subtract(1,'month').format("YYYY-MM");
    that.onSettleMonthChange(mothTotalDays);

    that.initTbSetData(that.dg.dgName);
    that.getDgList();
  },
  methods: {
    closeMd() {
      this.$emit("myClick", {state: false});
    },
    // 选择-结算月份-改变事件
    onSettleMonthChange(data) {
      const that = this, ps = that.dg.ps;

      // 设置-月份第一天
      ps.sTime = `${data}-01`;
      // 获取-月份天数
      let day = that.$moment(data, "YYYY-MM").daysInMonth();
      // 设置-月份最后一天
      ps.eTime = `${data}-${day}`;
    },
    // 查询表格数据
    queryDgList() {
      const that = this, U = that.U;

      if (!that.dg.ps.settleMonth) {
        U.qerror("请先选择结算月份");
      }else{
        that.getDgList();
      }
    },
    // 获取-表格数据
    getDgList() {
      let that = this, U = that.U, ps = U.scopy(that.dg.ps);
      
      delete ps.settleMonth;

      orderSer.getCanSettleList(ps).then((res) => {
        if (res.code === 1) {
          that.totalPay = res.totalPay;
          that.totalGath = res.totalGath;
          that.bankBalance = res.bankBalance;

          let list = res.data;
          list.forEach(it => {it.dgName = that.dg.dgName;});
          that.dg.list = list
          that.dg.total = res.count;
        }
      });
    },
    // 立即结算
    onSubmit() {
      const that = this, U = that.U, ps = that.dg.ps, {list} = that.dg;

      let isObj = list.find(it => it.isCheck != 1);
      if(!list || list.length == 0){
        U.qerror('没有需要报销的结算信息');
      }else if (isObj) {
        U.qerror('所选月份【存在未报销】的数据，不能结算');
      }else{
        let btlIds = list.map(it => it.id).join(',');
        // 结算名称
        let settleName = `${that.dg.ps.settleMonth.replace('-', '年')}月现金结算表`;
        let params = {
          btlIds,
          settleName,
          settleTime: ps.sTime,
        }
        orderSer.setBankMonthly(params).then(res => {
          if (res.code !== 1) {
            U.qerror(res.msg);
          }else{
            U.qsuccess(res.msg);

            that.closeMd();
            that.$emit('reloadDg');
          }
        });
      }
    },
  },
};
</script>